<template>
	<div class="layout-padding">
		<div class="layout-padding-auto layout-padding-view">
			<el-row>
				<div class="flex justify-between w-full mb8">
					<el-space>
						<el-popover trigger="click" :width="680" placement="bottom-start">
							<el-form :inline="false" :model="state.queryForm" @keyup.enter="getDataList" ref="queryRef" label-width="90px" size="small">
								<el-row>
									<el-col :span="12" class="mb20">
										<el-form-item :label="$t('alarmLogging.deptId')" prop="deptId">
											<el-tree-select
												v-model="state.queryForm.deptId"
												:data="parentData"
												:props="{ value: 'id', label: 'name', children: 'children', disabled: 'isLock' }"
												clearable
												filterable
												check-strictly
												tag-type="success"
												:render-after-expand="true"
												:placeholder="$t('alarmLogging.deptIdtip')"
												:teleported="false"
											/>
										</el-form-item>
									</el-col>
									<el-col :span="12" class="mb20">
										<el-form-item :label="$t('alarmLogging.deptLimit')" prop="deptLimit">
											<el-select clearable v-model="state.queryForm.deptLimit" :placeholder="$t('alarmLogging.deptLimittip')" :teleported="false">
												<el-option :label="$t('alarmLogging.deptLimitone')" :value="10" />
												<el-option :label="$t('alarmLogging.deptLimittwo')" :value="20" />
											</el-select>
										</el-form-item>
									</el-col>
									<el-col :span="12" class="mb20">
										<el-form-item :label="$t('alarmLogging.deviceTypeId')" prop="deviceTypeId">
											<el-select
												v-model="state.queryForm.deviceTypeId"
												clearable
												filterable
												:placeholder="$t('alarmLogging.deviceTypeIdtip')"
												@change="getModelList"
												:teleported="false"
											>
												<el-option
													v-for="item in deviceTypeList"
													:key="item.id"
													:value="item.id"
													:label="item.typeName"
													:disabled="item.state === 20"
												/>
											</el-select>
										</el-form-item>
									</el-col>

									<el-col :span="12" class="mb20">
										<el-form-item :label="$t('alarmLogging.deviceModelId')" prop="deviceModelId">
											<el-select
												v-model="state.queryForm.deviceModelId"
												clearable
												filterable
												:placeholder="$t('alarmLogging.deviceModelIdtip')"
												@change="getEventTypeList"
												:teleported="false"
											>
												<el-option
													v-for="item in deviceModelList"
													:key="item.id"
													:value="item.id"
													:label="item.deviceModelName"
													:disabled="item.state === 20"
												/>
											</el-select>
										</el-form-item>
									</el-col>

									<el-col :span="12" class="mb20">
										<el-form-item :label="$t('alarmLogging.eventTypeId')" prop="eventTypeId">
											<el-select
												v-model="state.queryForm.eventTypeId"
												clearable
												filterable
												:placeholder="$t('alarmLogging.eventTypeIdtip')"
												:teleported="false"
											>
												<el-option
													v-for="item in eventTypeList"
													:key="item.id"
													:value="item.id"
													:label="item.eventTypeName"
													:disabled="item.state === 10"
												/>
											</el-select>
										</el-form-item>
									</el-col>

									<el-col :span="12" class="mb20">
										<el-form-item :label="$t('alarmLogging.installLocationId')" prop="installLocationId">
											<el-select
												v-model="state.queryForm.installLocationId"
												filterable
												:placeholder="$t('alarmLogging.installLocationIdtip')"
												:teleported="false"
											>
												<el-option v-for="item in buildingOptions" :key="item.id" :label="item.address" :value="item.id" />
											</el-select>
										</el-form-item>
									</el-col>

									<el-col :span="12" class="mb20">
										<el-form-item :label="$t('alarmLogging.state')" prop="state">
											<el-select clearable v-model="state.queryForm.state" :placeholder="$t('alarmLogging.statetip')" :teleported="false">
												<el-option :label="$t('alarmLogging.handled')" :value="10" />
												<el-option :label="$t('alarmLogging.unhandle')" :value="20" />
											</el-select>
										</el-form-item>
									</el-col>
								</el-row>
							</el-form>

							<template #reference>
								<el-button link type="primary"
									>{{ $t('common.advancedSearch') }}<el-icon><ArrowDown /></el-icon>
								</el-button>
							</template>
						</el-popover>
						<el-input :placeholder="$t('alarmLogging.imeitip')" v-model="state.queryForm.imei" @keyup.enter="getDataList" />
						<el-button type="primary" @click="getDataList(true)">{{ $t('common.queryBtn') }}</el-button>
						<el-button icon="refresh" @click="resetQuery()"></el-button>
					</el-space>
					<div>
						<el-button
							type="warning"
							v-auth="'platform_alarmLogging_batch'"
							@click="BatchHandlingDialogRef.openDialog(selectObjs)"
							:disabled="!selectObjs.length"
							>批量处理</el-button
						>
						<el-button @click="hnadleExportDialog" v-auth="'platform_alarmLogging_export'">{{ $t('alarmLogging.exportAlarmRecord') }}</el-button>
					</div>
				</div>
			</el-row>
			<!-- <el-row>
				<div class="mb8" style="width: 100%">
					<el-button icon="folder-add" type="primary" class="ml10" @click="formDialogRef.openDialog()" v-auth="'platform_alarmLogging_add'">
						新 增
					</el-button>
					<el-button plain :disabled="multiple" icon="Delete" type="primary" v-auth="'platform_alarmLogging_del'" @click="handleDelete(selectObjs)">
						删除
					</el-button>
					<right-toolbar
						v-model:showSearch="showSearch"
						:export="'platform_alarmLogging_export'"
						@exportExcel="exportExcel"
						class="ml10 mr20"
						style="float: right"
						@queryTable="getDataList"
					></right-toolbar>
				</div>
			</el-row> -->
			<el-table
				:data="state.dataList"
				v-loading="state.loading"
				border
				:cell-style="tableStyle.cellStyle"
				:header-cell-style="tableStyle.headerCellStyle"
				@selection-change="selectionChangHandle"
			>
				<el-table-column type="selection" width="40" align="center" v-auth="'platform_alarmLogging_batch'" />
				<el-table-column type="index" :label="$t('alarmLogging.index')" width="65" />
				<el-table-column prop="imei" label="IMEI" show-overflow-tooltip min-width="160">
					<template #default="{ row }">
						<div class="flex justify-start">
							<el-button icon="DocumentCopy" link type="primary" size="small" @click="copyText(row.imei)"></el-button>
							<el-button type="primary" link @click="handleDetail(row.deviceId)" size="small">{{ row.imei }}</el-button>
						</div>
					</template>
				</el-table-column>
				<el-table-column prop="deviceTypeName" :label="$t('alarmLogging.deviceTypeName')" show-overflow-tooltip width="220">
					<template #default="{ row }">
						<span>
							{{ row.deviceTypeName }}
							-
							{{ row.deviceModelName }}
						</span>
					</template>
				</el-table-column>
				<el-table-column prop="address" :label="$t('alarmLogging.address')" show-overflow-tooltip min-width="150" />
				<el-table-column prop="eventTypeName" :label="$t('alarmLogging.eventTypeName')" show-overflow-tooltip min-width="150" />
				<el-table-column prop="alarmCauses" :label="$t('alarmLogging.alarmCauses')" show-overflow-tooltip min-width="180" />
				<el-table-column prop="deptName" :label="$t('alarmLogging.deptName')" show-overflow-tooltip width="220" />
				<el-table-column prop="createTime" :label="$t('alarmLogging.createTime')" show-overflow-tooltip width="220" />
				<el-table-column prop="confirmState" :label="$t('alarmLogging.confirmState')" show-overflow-tooltip min-width="120">
					<template #default="{ row }">
						<div>
							<span :style="{ color: getProcess(row.processTypeLevel)?.value }">{{ row?.processTypeName }}</span>
						</div>
					</template>
				</el-table-column>
				<el-table-column
					prop="smsAlarmSketch"
					:label="$t('alarmLogging.smsAlarmSketch')"
					:show-overflow-tooltip="{ popperClass: 'max-w-[280px]' }"
					min-width="180"
				>
					<template #default="{ row }">
						<div>
							<el-button link type="primary" @click="notificationDialogRef.openDialog(row.smsAlarmId, '短信')">{{
								row.smsAlarmSketch
							}}</el-button>
						</div>
					</template>
				</el-table-column>
				<el-table-column
					prop="telephoneAlarmSketch"
					:label="$t('alarmLogging.telephoneAlarmSketch')"
					:show-overflow-tooltip="{ popperClass: 'max-w-[280px]' }"
					min-width="180"
				>
					<template #default="{ row }">
						<div>
							<el-button link type="primary" @click="notificationDialogRef.openDialog(row.telephoneAlarmId, '电话')">{{
								row.telephoneAlarmSketch
							}}</el-button>
						</div>
					</template>
				</el-table-column>
				<el-table-column
					prop="officialAccountAlarmSketch"
					:label="$t('alarmLogging.officialAccountAlarmSketch')"
					:show-overflow-tooltip="{ popperClass: 'max-w-[280px]' }"
					min-width="180"
				>
					<template #default="{ row }">
						<div>
							<el-button link type="primary" @click="notificationDialogRef.openDialog(row.officialAccountAlarmId, '公众号')">{{
								row.officialAccountAlarmSketch
							}}</el-button>
						</div>
					</template>
				</el-table-column>
				<el-table-column prop="updateTime" :label="$t('alarmLogging.updateTime')" show-overflow-tooltip width="220" />
				<el-table-column prop="remarks" :label="$t('alarmLogging.remarks')" show-overflow-tooltip min-width="120" />
				<el-table-column :label="$t('common.action')" width="80" fixed="right">
					<template #default="scope">
						<!-- <el-button icon="edit-pen" text type="primary" v-auth="'platform_alarmLogging_edit'" @click="formDialogRef.openDialog(scope.row.id)"
							>编辑</el-button
						> -->
						<!-- <el-button icon="delete" text type="primary" v-auth="'platform_alarmLogging_del'" @click="handleDelete([scope.row.id])">删除</el-button> -->
						<el-popover placement="left" trigger="click" :width="80" :disabled="scope.row.state !== 20">
							<div class="flex justify-center">
								<el-space direction="vertical">
									<el-button
										@click="handling(scope.row.id, item)"
										v-for="item in processTypeOptions"
										:key="item.id"
										:color="getProcess(item.processTypeLevel)?.value"
										plain
										>{{ item.processTypeName }}</el-button
									>
								</el-space>
							</div>
							<template #reference>
								<el-button type="primary" size="small" link v-if="scope.row.state === 20">{{ $t('alarmLogging.handle') }}</el-button>
								<span class="text-info" v-else>{{ $t('alarmLogging.handled') }}</span>
							</template>
						</el-popover>
					</template>
				</el-table-column>
			</el-table>
			<pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" v-bind="state.pagination" />
		</div>

		<!-- 编辑、新增  -->
		<form-dialog ref="formDialogRef" @refresh="getDataList(false)" />
		<!-- 处理 -->
		<handling-form-dialog ref="handlingFormDialogRef" @refresh="getDataList(false)" />
		<!-- 批量处理 -->
		<batch-handling-dialog ref="BatchHandlingDialogRef" @refresh="getDataList(false)" />
		<!-- 通知记录 -->
		<notification-dialog ref="notificationDialogRef" />
		<!-- 导出 -->
		<el-dialog :title="$t('alarmLogging.exportAlarmRecord')" v-model="visible" :close-on-click-modal="false" draggable width="620px">
			<el-form :inline="false" :model="exportQueryForm" ref="exportQueryRef" label-width="90px">
				<el-form-item label="选择时间" prop="createTime" :rules="{ required: true, message: '请选择日期', trigger: 'change' }">
					<el-date-picker
						:end-placeholder="$t('syslog.inputEndPlaceholderTip')"
						:start-placeholder="$t('syslog.inputStartPlaceholderTip')"
						range-separator="To"
						type="datetimerange"
						v-model="exportQueryForm.createTime"
						value-format="YYYY-MM-DD HH:mm:ss"
					/>
				</el-form-item>
			</el-form>

			<template #footer>
				<span class="dialog-footer">
					<el-button @click="visible = false">{{ $t('common.cancelButtonText') }}</el-button>
					<el-button type="primary" @click="exportExcel">{{ $t('common.confirmButtonText') }}</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script setup lang="ts" name="systemAlarmLogging">
import { BasicTableProps, useTable } from '/@/hooks/table';
import { fetchList, delObjs } from '/@/api/alarm/alarmLogging';
import { useMessage, useMessageBox } from '/@/hooks/message';
import { deptTree } from '/@/api/admin/dept';
import { fetchListAll } from '/@/api/platform/basicDeviceType';
import { fetchListAll as fetchAllModelList } from '/@/api/platform/basicDeviceModel';
import { fetchListAll as fetchInstallListAll } from '/@/api/installation/basicInstallLocation';
import { fetchListAll as fetchEventTypeListAll } from '/@/api/alarm/alarmEventType';
import { fetchListAll as fetchProcessTypeListAll } from '/@/api/alarm/alarmProcessType';
import { useRouter } from 'vue-router';
import commonFunction from '/@/utils/commonFunction';
import { processTypeLevelOptions } from '../alarmProcessType/data';
import { useI18n } from 'vue-i18n';

const { t } = useI18n();
const router = useRouter();
const { copyText } = commonFunction();
// 引入组件
const FormDialog = defineAsyncComponent(() => import('./form.vue'));
const HandlingFormDialog = defineAsyncComponent(() => import('./components/handlingForm.vue'));
const BatchHandlingDialog = defineAsyncComponent(() => import('./components/batchHandling.vue'));
const notificationDialog = defineAsyncComponent(() => import('../alarmFaultLogging/components/notification.vue'));

// 定义查询字典

// 定义变量内容
const formDialogRef = ref();
const handlingFormDialogRef = ref();
const BatchHandlingDialogRef = ref();
const notificationDialogRef = ref();
const exportQueryRef = ref();
const parentData: any = ref([]);
const deviceTypeList: any = ref([]);
const deviceModelList: any = ref([]);
const eventTypeList: any = ref([]);
const buildingOptions = ref<any[]>([]);
const processTypeOptions = ref<any[]>([]);
// 搜索变量
const queryRef = ref();
const showSearch = ref(true);
const visible = ref(false);
// 多选变量
const selectObjs = ref([]) as any;
const multiple = ref(true);

const state: BasicTableProps = reactive<BasicTableProps>({
	queryForm: {},
	pageList: fetchList,
	descs: ['create_time'],
	createdIsNeed: false,
});
const exportQueryForm = reactive({
	createTime: '',
});

//  table hook
const { getDataList, currentChangeHandle, sizeChangeHandle, sortChangeHandle, downBlobFile, tableStyle } = useTable(state);

// 清空搜索条件
const resetQuery = () => {
	// 清空搜索条件
	queryRef.value?.resetFields();
	// 清空多选
	selectObjs.value = [];
	state.queryForm.imei = '';
	getDataList();
};

// 导出excel
const exportExcel = async () => {
	const valid = await exportQueryRef.value.validate().catch(() => {});
	if (!valid) return false;
	downBlobFile('/platform/alarmLogging/export', exportQueryForm, '报警记录.xlsx');
};

// 多选事件
const selectionChangHandle = (objs: { id: string }[]) => {
	selectObjs.value = objs.map(({ id }) => id);
	multiple.value = !objs.length;
};

// 删除操作
const handleDelete = async (ids: string[]) => {
	try {
		await useMessageBox().confirm('此操作将永久删除');
	} catch {
		return;
	}

	try {
		await delObjs(ids);
		getDataList();
		useMessage().success('删除成功');
	} catch (err: any) {
		useMessage().error(err.msg);
	}
};
const getDeptData = async () => {
	deptTree().then((res) => {
		parentData.value = res.data;
	});
};
getDeptData();
// 获取设备数据
const getDeviceTypes = () => {
	fetchListAll({ state: 20 }).then((res) => {
		deviceTypeList.value = res.data;
	});
};
getDeviceTypes();
// 查询设备型号
const getModelList = (deviceTypeId: string) => {
	state.queryForm.deviceModelId = null;
	state.queryForm.eventTypeId = null;
	fetchAllModelList({ deviceTypeId, state: 20 }).then((res) => {
		deviceModelList.value = res.data;
	});
};
// 查询事件类型
const getEventTypeList = (deviceModelId: string) => {
	state.queryForm.eventTypeId = null;
	fetchEventTypeListAll({ deviceModelId, state: 20, deviceTypeId: state.queryForm.deviceTypeId }).then((res) => {
		eventTypeList.value = res.data.filter((d: { alarmTypeCode: string }) => {
			return d.alarmTypeCode === 'RULES_ALARM' || d.alarmTypeCode === 'DEVICE_ALARM';
		});
	});
};
const getBuildings = () => {
	fetchInstallListAll().then((res) => {
		buildingOptions.value = res.data;
	});
};
getBuildings();
const getProcessTypes = () => {
	fetchProcessTypeListAll({ state: 20 }).then((res) => {
		processTypeOptions.value = res.data;
	});
};
getProcessTypes();
const handling = (id: any, propcess: any) => {
	handlingFormDialogRef.value.openDialog(id, propcess);
};
const handleDetail = (id: string) => {
	router.push({ path: '/platform/basicDevice/facilityDetails', query: { id, type: '3' } });
};
// 查询处理类型的颜色
const getProcess = (processTypeLevel: number) => {
	const item = processTypeLevelOptions.find((d) => d.id === processTypeLevel);
	return item;
};
const hnadleExportDialog = () => {
	visible.value = true;
	nextTick(() => {
		exportQueryRef.value?.resetFields();
	});
};
onMounted(() => {
	let imei = history.state.imei;
	if (imei) {
		state.queryForm.imei = imei;
		history.state.imei = null;
	}
	getDataList();
});
</script>
